<template>
  <!-- 创建提货单 -->
  <div>
    <el-table
      :data="tableData"
      @selection-change="handleSelectionChange"
      class="text-sm margin-bottom"
    >
      <el-table-column type="selection" width="55">
        <template slot="header" slot-scope="scope">
          <span class="text-sm">全选</span>
        </template>
      </el-table-column>
      <el-table-column label="运单号" prop="waybillNo"></el-table-column>
      <el-table-column label="参考号" prop="referenceNo"></el-table-column>
      <el-table-column
        label="预报件数"
        prop="customerTotalPackages"
      ></el-table-column>
      <el-table-column
        label="预报重量(KG)"
        prop="customerActualWeight"
      ></el-table-column>
      <el-table-column
        label="预报体积(CBM)"
        prop="customerVolume"
      ></el-table-column>
      <template v-if="takeDeliveryOfGoodsId">
        <el-table-column label="是否已预约">是</el-table-column>
      </template>
      <template v-else>
        <el-table-column label="是否已预约">否</el-table-column>
      </template>
    </el-table>
    <el-form
      :inline="false"
      ref="formData"
      :model="formData"
      :rules="formDataRules"
      style="padding:20px"
      size="mini"
      label-width="120px"
    >
      <el-row>
        <el-col :span="8">
          <el-form-item label="件数" prop="takeDeliveryOfGoodsCount">
            <el-input v-model="formData.takeDeliveryOfGoodsCount" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="重量(KG)" prop="takeDeliveryOfGoodsWeight">
            <el-input v-model="formData.takeDeliveryOfGoodsWeight" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="体积(CBM)" prop="takeDeliveryOfGoodsVolume">
            <el-input v-model="formData.takeDeliveryOfGoodsVolume" clearable />
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="提货时间" prop="appointmentPickupDate">
        <el-date-picker
          type="datetime"
          v-model="formData.appointmentPickupDate"
          style="width:178px"
          value-format="yyyy-MM-dd HH:mm:ss"
          placeholder="选择日期时间"
          :picker-options="pickerOptions"
        />
      </el-form-item>
      <!--<el-form-item label="仓库地址" prop="appointmentPickupDate">
        <el-select
          v-model="locationValue"
          placeholder="请选择"
          size="mini"
          class="margin-lr"
        >
          <el-option
            v-for="item in options"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </el-form-item>-->
      <div class="flex justify-end">
        <el-button type="text" @click="btnData" class="text-sm"
          >新增收货地址</el-button
        >
      </div>
      <div v-show="isShow">
        <el-form-item prop="provincesModel" label="联系地址">
          <el-cascader
            v-model="formData.provincesModel"
            filterable
            :options="cityOptions"
            @change="cityHandleChange"
          />
        </el-form-item>
        <el-form-item prop="addressModel" label="详细地址">
          <el-input
            v-model="formData.addressModel"
            clearable
            placeholder="请填写详细地址"
          />
        </el-form-item>
        <el-row>
          <el-col :span="8">
            <el-form-item prop="linkManModel" label="联系人">
              <el-input
                v-model="formData.linkManModel"
                placeholder="请填写联系人"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item prop="contactWayModel" label="联系方式">
              <el-input
                v-model.number="formData.contactWayModel"
                placeholder="请填写联系方式"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-button size="mini" type="primary" @click="saveCustomerPickUpAddress"
          >保存提货信息</el-button
        >
        <el-button size="mini" type="primary" @click="cancelEdit"
          >取消编辑</el-button
        >
      </div>
      <el-divider></el-divider>
      <el-form-item label="提货地址" prop="pickupaddress">
        <el-select
          v-model="pickupaddress"
          style="width:400px"
          class="margin-right-xl"
        >
          <el-option
            v-for="(item, value) in customerPickupAddresses"
            :key="value"
            :label="
              item.linkMan +
                item.state +
                item.city +
                item.area +
                item.street +
                item.address +
                item.contactWay
            "
            :value="item.id"
          >
            <span width="10%">{{ item.linkMan }}</span>
            <span>{{ item.state }}</span>
            <span>{{ item.city }}</span>
            <span>{{ item.area }}</span>
            <span>{{ item.street }}</span>
            <span>{{ item.address }}</span>
            <span width="20%">{{ item.contactWay }}</span>
          </el-option>
        </el-select>

        <!-- <p
                class="text-sm"
                style="cursor: pointer"
                v-if="displayAdd === true"
                @click="downAdd"
              >
                更多提货地址<i class="el-icon-arrow-down"></i>
              </p>-->
        <p
          class="text-sm"
          style="cursor: pointer;color:red"
          @click="changeDefault"
        >
          设置选择地址为默认地址<i class="el-icon-arrow-up"></i>
        </p>
      </el-form-item>

      <el-row>
        <el-col :span="8">
          <el-form-item
            label="备用手机"
            prop="takeDeliveryOfGoodsLinkPhoneSpare"
          >
            <el-input
              v-model="formData.takeDeliveryOfGoodsLinkPhoneSpare"
              style="width:200px"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="运单类型" prop="takeDeliveryOrderType">
            <el-select v-model="formData.takeDeliveryOrderType" clearable>
              <el-option value="10" label="海运">海运</el-option>
              <el-option value="20" label="空运">空运</el-option>
              <el-option value="30" label="海运+空运">海运+空运</el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <div
        class="text-sm text-bold margin-left margin-bottom"
        style="color:red; padding:10px;"
      >
        温馨提示：如需取消提货，请及时电话通知我司销售人员，如司机已在途中，将产生返空费
      </div>
      <el-form-item label="备注说明">
        <el-input
          type="textarea"
          :rows="3"
          placeholder="请在此处备注您的提货特殊需求."
          v-model="formData.sysRemark"
        />
      </el-form-item>
      <div>
        <el-button type="primary" size="mini" @click="commitData"
          >保存</el-button
        >
      </div>
    </el-form>
  </div>
</template>
<script>
import { ajax } from "@/store/yg/common/utils";
import axios from "axios";
import * as constant from "@/store/yg/common/constant";
import { untransform } from "../../../../../store/yg/common/uri";
import { getPcas } from "@/utils/city-pcas.js";
import Row from "../../../../yg/layout/main/page/wrapper/form/Row.vue";
import moment from "moment";
import "moment/locale/zh-cn";
moment.locale("zh-cn");

export default {
  components: { Row },
  data() {
    return {
      // 设置只能选择当前日期及之后的日期
      pickerOptions: {
        selectableRange: (() => {
          let data = new Date();
          let hour = data.getHours();
          let minute = data.getMinutes();
          let second = data.getSeconds();
          return [`${hour}:${minute}:${second} - 23:59:59`];
        })(),
        disabledDate(time) {
          // let date = new Date();
          // date.setFullYear(date.getFullYear() + 2);
          // date.setDate(date.getDate() - 1);
          return time.getTime() < Date.now() - 8.64e7;
        }
      },
      // defaultTime: new Date(),
      displayAdd: true,
      disInput: true,
      isShow: false,
      customerPickupAddresses: {},
      // takeDeliveryOrderType: "",
      selectionList: [],
      tableData: [],
      customerId: "",
      takeDeliveryOfGoodsId: "",
      selectAddr: "",
      cityOptions: getPcas(),
      form: {
        id: "",
        linkMan: "",
        contactWay: "",
        defaultValue: "",
        street: "",
        address: "",
        state: "",
        city: "",
        area: "",
        provinces: [],
        cuser: ""
      },
      formData: {
        takeDeliveryOfGoodsCount: "",
        takeDeliveryOfGoodsWeight: "",
        takeDeliveryOfGoodsVolume: "",
        appointmentPickupDate: "",
        takeDeliveryOrderType: "",
        waybills: [],
        customerId: "",
        customerCode: "",
        linkManModel: "",
        contactWayModel: "",
        provincesModel: "",
        addressModel: ""
      },
      takeDeliveryOrderTypeMap: {},
      pickupaddress: "",
      formDataRules: {
        takeDeliveryOfGoodsCount: [
          { required: true, message: "请填写件数", trigger: "blur" }
        ],
        takeDeliveryOfGoodsWeight: [
          { required: true, message: "请填写重量", trigger: "blur" }
        ],
        takeDeliveryOfGoodsVolume: [
          { required: true, message: "请填写体积", trigger: "blur" }
        ],
        appointmentPickupDate: [
          { required: true, message: "请选择提货时间", trigger: "change" }
        ],
        linkManModel: [
          { required: true, message: "请填写联系人", trigger: "blur" }
        ],
        contactWayModel: [
          { required: true, message: "请填写联系方式", trigger: "blur" },
          { pattern: /^1[34578]\d{9}$/, message: "请填写正确的手机号码" }
        ],
        addressModel: [
          { required: true, message: "请填写详细地址", trigger: "blur" }
        ],
        provincesModel: [
          { required: true, message: "请选择联系地址", trigger: "change" }
        ],
        takeDeliveryOrderType: [
          { required: true, message: "请选择运单类型", trigger: "change" }
        ]
      }
    };
  },
  computed: {},
  watch: {
    "formData.appointmentPickupDate": {
      handler(newValue, oldValue) {
        if (newValue) {
          let date = new Date();
          let nowDate = moment(date).format("HH:mm:ss");
          if (
            moment(date).format("yyyy-MM-DD") ===
            moment(newValue).format("yyyy-MM-DD")
          ) {
            console.log("当前时间", nowDate);
            this.pickerOptions.selectableRange = `${nowDate}-23:59:59`;
          } else {
            this.pickerOptions.selectableRange = `00:00:00-23:59:59`;
          }
        }
      },
      // deep: true,
      immediate: true
    }
  },
  mounted() {
    this.initData();
    this.takeDeliveryOrderTypeSource("takeDeliveryOrderTypeSource");
    for (let i of this.cityOptions) {
      for (let v of i.children) {
        for (let k of v.children) {
          k.children.push({
            label: "暂不选择",
            value: ""
          });
        }
      }
    }
  },
  methods: {
    async takeDeliveryOrderTypeSource(bean) {
      var uri = "/api/entry/source?bean=" + bean;
      const res = await axios.post(constant.API_SERVER + uri).then(
        response => {
          this.takeDeliveryOrderTypeMap = response.data;
        },
        error => {
          console.info(error);
        }
      );
    },
    initData() {
      this.customerId = this.$store.state.edit.row["id"];
      ajax("editTakeDeliveryOfGoods", { id: this.customerId }).then(
        res => {
          if (res.code == 200) {
            // console.log("res.data",res.data);
            var data = res.data;
            this.tableData = data.simpleWaybillQueries;
            this.customerPickupAddresses = data.customerPickupAddresses;
            // console.log(this.formData.pickupaddress);
            for (let key in this.customerPickupAddresses) {
              if (this.customerPickupAddresses[key].defaultValue == 1) {
                this.pickupaddress == this.customerPickupAddresses[key].id;
                break;
              }
            }
          } else {
            this.$message.error(res.message);
          }
        },
        error => {
          console.log(error);
        }
      );
    },
    appointmentPickupDateCheck(){
      var arr = [];
      for (let i of this.selectionList){
        if(arr.indexOf(i.loadingPort)<0) {
          arr.push(i.loadingPort);
        }
      }
      if (arr.length<1){
        this.$message.error("请先选择运单");
        return;
      }
      ajax("appointmentPickupDateCheck", { portList: arr, appointmentPickupDate:this.formData.appointmentPickupDate}).then(
        res => {
          if (res.code != 200) {
            if (res.message) {
              this.$message.error(res.message);
            }else{
              this.$message.error("提货时间有误");
            }
            this.formData.appointmentPickupDate = "";
          }
        },
        error => {
          console.log(error);
        }
      );
    },
    cityHandleChange(val) {
      console.log("this.val", val);
      if (!val) return;
      if (val[3] === "暂不选择") {
        val[3] = "";
      }
      for (let i of this.cityOptions) {
        for (let v of i.children) {
          for (let k of v.children) {
            for (let j of k.children) {
              if (j.label === "暂不选择") {
                j.label = "";
              }
            }
          }
        }
      }
      this.form.state = val[0];
      this.form.city = val[1];
      this.form.area = val[2];
      this.form.street = val[3];
    },
    clearValidateFormAll() {
      this.$refs["formData"].clearValidate([
        "takeDeliveryOfGoodsCount",
        "takeDeliveryOfGoodsWeight",
        "takeDeliveryOfGoodsVolume",
        "appointmentPickupDate",
        "takeDeliveryOrderType"
      ]);
    },
    clearValidateForm() {
      this.$refs["formData"].clearValidate([
        "linkManModel",
        "contactWayModel",
        "provincesModel",
        "addressModel"
      ]);
    },
    commitData() {
      // debugger;
      //console.log(this.pickupaddress)
      for (var i of this.selectionList) {
        i["waybillId"] = i.id;
      }
      // if (this.selectionList.length < 1) {
      //   this.$message.error("请先选择数据");
      //   return;
      // }
      this.clearValidateForm();
      let flag = true;
      this.$refs["formData"].validateField(
        [
          "takeDeliveryOfGoodsCount",
          "takeDeliveryOfGoodsWeight",
          "takeDeliveryOfGoodsVolume",
          "appointmentPickupDate",
          "takeDeliveryOrderType"
        ],
        valid => {
          if (valid !== "") {
            flag = false;
          }
          //console.log(valid==="");
        }
      );
      if (
        this.formData.takeDeliveryOfGoodsCount <= 0 ||
        this.formData.takeDeliveryOfGoodsWeight <= 0 ||
        this.formData.takeDeliveryOfGoodsVolume <= 0
      ) {
        this.$message.error("数据必须大于0");
        return;
      }
      if (flag) {
        if (!this.pickupaddress) {
          this.$message.error("请先选择提货地址");
          return;
        }

        this.formData.customerCode = this.$store.state.edit.row["customerCode"];
        this.formData.customerId = this.customerId;
        this.customerPickupAddresses.forEach(element => {
          if (element.id == this.pickupaddress) {
            this.formData["takeDeliveryOfGoodsProvince"] = element.state;
            this.formData["takeDeliveryOfGoodsCity"] = element.city;
            this.formData["takeDeliveryOfGoodsArea"] = element.area;
            this.formData["takeDeliveryOfGoodsStreet"] = element.street;
            this.formData["takeDeliveryOfGoodsAddress"] = element.address;
            this.formData["takeDeliveryOfGoodsLinkMan"] = element.linkMan;
            this.formData["takeDeliveryOfGoodsLinkPhone"] = element.contactWay;
          }
        });
        this.formData.waybills = this.selectionList;
        let seaairWaybillType = "";
        if (this.formData.takeDeliveryOrderType == 10) {
          seaairWaybillType = "海运";
        } else if (this.formData.takeDeliveryOrderType == 20) {
          seaairWaybillType = "空运";
        } else if (this.formData.takeDeliveryOrderType == 30) {
          seaairWaybillType = "海运+空运";
        }
        // if (
        //   this.formData.sysRemark != "" &&
        //   this.formData.sysRemark != null &&
        //   this.formData.sysRemark != undefined
        // ) {
        //   this.formData.sysRemark =
        //     seaairWaybillType + "\n" + this.formData.sysRemark;
        // } else {
        //   this.formData.sysRemark = seaairWaybillType;
        // }

        let oldDate = new Date(this.formData.appointmentPickupDate);
        let time = oldDate.getTime();
        let nowDate = new Date();
        let nowTime = nowDate.getTime();
        if (time < nowTime) {
          this.$message.error("提货时间必须大于当前时间");
        } else {
          this.$confirm(
            "我司将尽快安排车辆，请留意手机信息接收提货司机信息，另请尽快创建运单，以方便我司安排货物入库处理",
            "确认操作",
            {
              confirmButtonText: "确认",
              cancelButtonText: "取消",
              type: "warning"
            }
          )
            .then(() => {
              ajax("saveTakeDeliveryOfGoods", this.formData).then(
                res => {
                  if (res.code == 200) {
                    this.$message.success("添加成功");
                  } else {
                    this.$message.error(res.message);
                  }
                },
                error => {
                  console.log(error);
                }
              );
            })
            .catch(() => {});
        }
      }
    },
    saveCustomerPickUpAddress() {
      this.clearValidateFormAll();
      let flag = true;
      this.$refs["formData"].validateField(
        ["linkManModel", "contactWayModel", "provincesModel", "addressModel"],
        valid => {
          if (valid !== "") {
            flag = false;
          }
          //console.log(valid==="");
        }
      );
      if (flag) {
        if (
          this.customerId == null ||
          this.customerId == "" ||
          this.customerId == undefined
        ) {
          this.$message.error("客户ID为空！", {
            icon: 0
          });
          return false;
        }
        this.form.contactWay = this.formData.contactWayModel;
        this.form.linkMan = this.formData.linkManModel;
        this.form.provinces = this.formData.provincesModel;
        this.form.address = this.formData.addressModel;
        this.form.cuser = this.customerId;
        console.log("form", this.form);
        ajax("saveCustomerPickUpAddress", this.form).then(
          res => {
            if (res.code == 200) {
              this.$message.success("添加成功");
              this.initData();
            } else {
              this.$message.error("添加失败");
            }
          },
          error => {
            console.log(error);
          }
        );
      } else {
        //console.log("验证不通过");
      }
    },
    changeDefault(index) {
      // debugger;
      if (!this.customerId) {
        this.$message.error("客户id为空");
        return;
      }
      if (!this.pickupaddress) {
        this.$message.error("没选择地址");
        return;
      }
      this.$confirm("是否将选择地址设为默认地址?", "确认操作", {
        confirmButtonText: "是",
        cancelButtonText: "否",
        type: "warning"
      })
        .then(() => {
          ajax("setDefaultPickUpAddress", {
            customerId: this.customerId,
            addressId: this.pickupaddress.id
          }).then(
            res => {
              if (res.code == 200) {
                this.$message.success("设置成功");
                this.initData();
                this.isShow = false;
              } else {
                this.$message.error("设置失败");
              }
            },
            error => {
              console.log(error);
            }
          );
        })
        .catch(() => {});
    },
    handleSelectionChange(val) {
      this.selectionList = val;
      if (this.selectionList.length < 1) {
        this.formData.takeDeliveryOfGoodsCount = 0;
        this.formData.takeDeliveryOfGoodsWeight = 0;
        this.formData.takeDeliveryOfGoodsVolume = 0;
        return;
      }
      let customerTotalPackages = 0;
      let customerActualWeight = 0;
      let customerVolume = 0;
      for (const i of this.selectionList) {
        if (i.customerTotalPackages) {
          customerTotalPackages += i.customerTotalPackages;
          this.formData.takeDeliveryOfGoodsCount = customerTotalPackages;
        }
        if (i.customerActualWeight) {
          customerActualWeight =
            (Number(customerActualWeight) * 1000 +
              Number(i.customerActualWeight) * 1000) /
            1000;
          this.formData.takeDeliveryOfGoodsWeight = customerActualWeight;
        }
        if (i.customerVolume) {
          customerVolume =
            (Number(customerVolume) * 1000 + Number(i.customerVolume * 1000)) /
            1000;
          this.formData.takeDeliveryOfGoodsVolume = customerVolume;
        }
      }
    },
    upAdd() {
      this.displayAdd = true;
      this.disInput = false;
    },
    downAdd() {
      this.displayAdd = false;
      this.disInput = true;
    },

    cancelEdit() {
      this.clearValidateForm();
      (this.form = {
        id: "",
        linkMan: "",
        contactWay: "",
        defaultValue: "",
        street: "",
        address: "",
        state: "",
        city: "",
        area: "",
        provinces: [],
        cuser: ""
      }),
        (this.formData.linkManModel = "");
      this.formData.contactWayModel = "";
      this.formData.provincesModel = "";
      this.formData.addressModel = "";
      this.isShow = false;
    },
    btnData() {
      this.isShow = true;
    }
  }
};
</script>
